/*
 * SteepTimer - A timer designed for tea fanatics
 * Copyright (C) 2011  Wesley Crossman
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "TeaOptionsDialog.h"
#include "ui_TeaOptionsDialog.h"
#include "TeaSound.h"
#include <QSettings>
#include <QTimer>
#include <QDebug>

TeaOptionsDialog::TeaOptionsDialog(QWidget *parent) :
            QDialog(parent, Qt::Dialog|Qt::MSWindowsFixedSizeDialogHint),
            m_mute(false),
            m_ui(new Ui::TeaOptionsDialog) {
    m_ui->setupUi(this);

    connect(m_ui->btnPlay, SIGNAL(clicked()), SLOT(play()) );

    m_previewTimer = new QTimer(this);
    m_previewTimer->start(1000);
    connect( m_previewTimer, SIGNAL(timeout()), SLOT(previewTimerTimeout()) );

    loadSettings();

    connect(m_ui->chkUseTrayIcon, SIGNAL(toggled(bool)), SLOT(updatePreview()) );
    connect(m_ui->chkTeabag, SIGNAL(toggled(bool)), SLOT(updatePreview()) );
    connect(m_ui->cmbColor, SIGNAL(currentIndexChanged(int)), SLOT(updatePreview()) );
    connect(m_ui->cmbTea, SIGNAL(currentIndexChanged(int)), SLOT(updatePreview()) );
    connect(m_ui->cmbVessel, SIGNAL(currentIndexChanged(int)), SLOT(vesselChanged()) );

#ifndef Q_OS_WIN
    m_ui->chkRunAutomatically->setEnabled(false);
#endif
}

TeaOptionsDialog::~TeaOptionsDialog() {
    TeaSound::instance()->stop();
    delete m_ui; m_ui = NULL;
}

void TeaOptionsDialog::saveSettings() {
    m_previewSettings.saveToSettings();
    QSettings settings;
    settings.setValue("settings/useTrayIcon", m_ui->chkUseTrayIcon->isChecked());
    settings.setValue("settings/soundEnabled", m_ui->chkPlaySoundWithAlarm->isChecked());

    int soundRepeat = 0;
    bool soundDelay = false;
    switch (m_ui->cmbAlarmRepeat->currentIndex()) {
    case 0: break;
    case 1: soundRepeat = 1; soundDelay = true; break;
    case 2: soundRepeat = 1; break;
    case 3: soundRepeat = 2; soundDelay = true; break;
    case 4: soundRepeat = 2; break;
    case 5: soundRepeat = -1; soundDelay = true; break;
    case 6: soundRepeat = -1; break;
    default: Q_ASSERT(false); break;
    }
    settings.setValue("settings/soundRepeat", soundRepeat);
    settings.setValue("settings/soundDelay", soundDelay);

#ifdef Q_OS_WIN
    QSettings runSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
                          QSettings::NativeFormat);
    if (m_ui->chkRunAutomatically->isChecked()) {
        runSettings.setValue( "SteepTimer", QString("\"%1\" /startup")
                              .arg(qApp->applicationFilePath().replace("/", "\\")) );
    } else {
        runSettings.remove("SteepTimer");
    }
    m_ui->chkRunAutomatically->setChecked(runSettings.value("SteepTimer").isValid());
#endif
}

void TeaOptionsDialog::loadSettings() {
    QSettings settings;

    m_mute = true;
    QList < SoundSettings > soundSettings = TeaSound::instance()->getSounds();
    int soundIndex = -1;
    QString soundFile = settings.value("settings/sound").toString();
    for (int a=0;a<soundSettings.size();++a) {
        if (soundSettings[a].m_filename == soundFile) soundIndex = a;
        m_ui->cmbAlarmSound->addItem(soundSettings[a].m_title);
    }
    if (soundIndex > -1) {
        m_ui->cmbAlarmSound->setCurrentIndex(soundIndex);
    }
    m_mute = false;

    m_ui->chkPlaySoundWithAlarm->setChecked(settings.value("settings/soundEnabled").toBool());
    m_ui->chkUseTrayIcon->setChecked(settings.value("settings/useTrayIcon").toBool());
    m_ui->chkTeabag->setChecked(m_previewSettings.m_teabag);
    m_ui->cmbVessel->setCurrentIndex(m_previewSettings.m_vessel);
    m_ui->cmbColor->setCurrentIndex(m_previewSettings.m_color-1);
    m_ui->cmbTea->setCurrentIndex(m_previewSettings.m_type-1);
    int repeat = settings.value("settings/soundRepeat").toInt()*2;
    int delay = settings.value("settings/soundDelay").toBool() ? 1 : 0;
    if (!repeat) {
    } else if (repeat == -2) {
        repeat = 6-delay;
    } else {
        repeat -= delay;
    }
    m_ui->cmbAlarmRepeat->setCurrentIndex(repeat);

#ifdef Q_OS_WIN
    QSettings runSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
                          QSettings::NativeFormat);
    m_ui->chkRunAutomatically->setChecked(runSettings.value("SteepTimer").isValid());
#endif

    updatePreview();
}

void TeaOptionsDialog::play(int index) {
    if (!m_mute) {
        if (index == -1) index = m_ui->cmbAlarmSound->currentIndex();
        TeaSound::instance()->play(TeaSound::instance()->getSounds()[index].m_filename);
    }
}

void TeaOptionsDialog::updatePreview() {
    m_previewSettings = TeaIconSettings(
            static_cast < TeaIcon::Vessel >(m_ui->cmbVessel->currentIndex()),
            true,
            static_cast < TeaIcon::CupColor >(m_ui->cmbColor->currentIndex()+1),
            static_cast < TeaIcon::DrinkType >(m_ui->cmbTea->currentIndex()+1),
            m_ui->chkTeabag->isChecked());
    m_previewRunning = TeaIcon::instance()->generateIcon(m_previewSettings);
    m_previewSettings.m_running = false;
    m_previewOff = TeaIcon::instance()->generateIcon(m_previewSettings);
    m_isPreviewRunning = true;
    m_ui->lblIcon->setPixmap(m_previewRunning);
}

void TeaOptionsDialog::previewTimerTimeout() {
    if (m_ui->chkUseTrayIcon->isChecked()) {
        m_isPreviewRunning = !m_isPreviewRunning;
        m_ui->lblIcon->setPixmap(m_isPreviewRunning ? m_previewRunning : m_previewOff);
    }
}

void TeaOptionsDialog::vesselChanged() {
    bool cup = (m_ui->cmbVessel->currentIndex() < TeaIcon::Gaiwan);
    m_ui->cmbColor->setEnabled(cup);
    m_ui->cmbTea->setEnabled(cup);
    m_ui->chkTeabag->setEnabled(cup);
    updatePreview();
}

void TeaOptionsDialog::on_cmbAlarmSound_currentIndexChanged(int index) {
    if (index > -1) {
        play(index);
        m_ui->lblSoundCopyright->setText(
                tr("Clip by <a href='%2'>%1</a> (<a href='%3'>license</a>)")
                .arg(TeaSound::instance()->getSounds()[index].m_author)
                .arg(TeaSound::instance()->getSounds()[index].m_url.toString())
                .arg(TeaSound::instance()->getSounds()[index].m_licenseUrl.toString()) );
    }
}
